package db

import (
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	. "goweb/models"
	"log"
)

type OrdeDb struct {
	Db *gorm.DB
}

func (o *OrdeDb) Init() {
	var err error

	o.Db, err = gorm.Open("mysql", DatabaseUrl)

	if err != nil {
		panic("连接数据库失败!\terr:" + err.Error())
	}

	o.Db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&DemoOrder{})
}

//查询所有订单
func (o *OrdeDb) FindOrders() ([]DemoOrder, error) {
	var orders []DemoOrder

	if err := o.Db.Find(&orders).Error; err != nil {
		return nil, err
	}

	return orders, nil
}

//根据Order_no查询
func (o *OrdeDb) FindOrderByOrderNo(orderNo string) (DemoOrder, error) {
	var order DemoOrder

	if err := o.Db.Where("order_no = ?", orderNo).First(&order).Error; err != nil {
		return DemoOrder{}, err
	}

	return order, nil
}

//增加记录,增加事务操作
func (o *OrdeDb) AddOrder(order DemoOrder) error {
	tx := o.Db.Begin()
	err := tx.Create(&order).Error

	if err != nil {
		log.Println("回滚了")
		tx.Rollback()
		return err
	}

	tx.Commit()
	return nil
}

//根据user_name来模糊查询
func (o *OrdeDb) FindOrderByLikeUserName(userName string) ([]DemoOrder, error) {
	var orders []DemoOrder

	if err := o.Db.Where("user_name like ?", "%"+userName+"%").Find(&orders).Error; err != nil {
		return nil, err
	}

	return orders, nil
}

//根据创建时间与金额排序
func (o *OrdeDb) FindOrderOrderByCreatedAtAndAmount() ([]DemoOrder, error) {
	var orders []DemoOrder

	if err := o.Db.Order("created_at, amount").Find(&orders).Error; err != nil {
		return nil, err
	}

	return orders, nil
}

//更新,加入事务操作
func (o *OrdeDb) UpdateOrder(order DemoOrder) error {
	tx := o.Db.Begin()

	err := tx.Save(&order).Error

	if err != nil {
		tx.Rollback()
		return err
	}

	tx.Commit()
	return nil
}

//将文件路径持久化
func (o *OrdeDb) SaveFileUrl(FileUrl string, id int) error {
	order, err := o.FindOrderById(id)

	order.FileUrl = FileUrl

	o.UpdateOrder(order)

	return err
}

//根据id查询
func (o *OrdeDb) FindOrderById(id int) (DemoOrder, error) {
	var order DemoOrder

	if err := o.Db.Where("id = ?", id).First(&order).Error; err != nil {
		return DemoOrder{}, err
	}

	return order, nil
}
